/*
 * dm_initd.cpp
 *
 *  Created on: 2016年11月20日
 *      Author: work
 */

#include <boost/program_options.hpp>
#include <dm/os/log/logger.hpp>
#include <dm/scada/taskmgr.hpp>
#include <dm/scada/taskproc.hpp>
#include <string>
#include <iostream>

using namespace std;
using namespace boost::program_options;
using namespace dm::scada;

bool execTask( const char* /*cmd*/,const char* /*args*/ ){
	// todo 创建进程启动任务
	return true;
}

static const char* logModule = "initd.dm";

int main( int argc,char* argv[] ){
	options_description desc("平台守护进程。");
	desc.add_options()
			("help,h","显示帮助信息")
			("version,v","显示版本信息")
			("show,s","显示任务信息")
			("monitor,m","监视任务状态")
			("delete,d","删除任务管理信息")
			;

	variables_map vm;
	try{
		store(parse_command_line(argc,argv,desc),vm);
		notify(vm);
	}catch( std::exception& ex ){
		cout << ex.what()<<endl;
		return 1;
	}

	if( vm.count("version") ){
		cout <<"build on "<<__DATE__<<endl;
		return 1;
	}

	if( vm.count("help") ){
		cout <<desc<<endl;
		return 1;
	}

	if( vm.count("show") ){
		const CTaskCfg& cfg = CTaskCfg::ins();
		cout <<"系统任务最大容量:"<<cfg.MaxSize<<endl;
		cout <<"目前配置任务数： "<<cfg.size()<<endl;
		for( dm::scada::size_t task=0;task<cfg.size();++task ){
			const CTaskInfo* ti = cfg.info(task);
			cout <<"<"<<task+1<<"> "
					<<" 命令行："<<ti->cmd.c_str()
					<<" 参数："<<ti->args.c_str()
					<<" 描述:"<<ti->desc.c_str()
					<<" 启动方式："<<ti->type
					<<" year:"<<ti->year
					<<" month:"<<ti->month
					<<" day:"<<ti->day
					<<" week:"<<ti->wday
					<<" hour:"<<ti->hour
					<<" min:"<<ti->min
					<<" sec:"<<ti->sec
					<<endl;
		}
	}else	if( vm.count("monitor") ){
		CTaskMgr& tm = CTaskMgr::ins();
		cout <<"系统任务最大容量:"<<tm.MaxSize<<endl;
		cout <<"目前配置任务数： "<<tm.size()<<endl;
		cout <<" 序号\t状态\t进程号\t上次执行时刻\t下次执行时刻\t运行次数"<<endl;
		for( dm::scada::size_t task=0;task<tm.size();++task ){
			const CTaskStatus* st = tm.status(task);
			cout <<"<"<<task+1<<">\t";
			switch(st->state){
			case CTaskStatus::UnRun:
				cout <<"未运行";
				break;
			case CTaskStatus::Running:
				cout <<"运行中";
				break;
			case CTaskStatus::Exited:
				cout <<"正常退出";
				break;
			case CTaskStatus::Stoped:
				cout <<"中止";
				break;
			}

			cout <<"\t"<<st->pid<<"\t"<<st->lastRun<<"\t"<<st->nextRun<<"\t"<<st->runTimes<<endl;
		}
	}else if( vm.count("delete") ){
		cout <<"删除任务管理信息 ";
		if(CTaskMgr::ins().remove() )
			cout <<"成功";
		else
			cout <<"失败";

		cout <<endl;
		return 0;
	}else{
		// 运行守护
		CTaskProc proc("dm_initd");
		CTaskMgr& tm = CTaskMgr::ins();

		log().debug(STATICMODULE "start daemon dm_initd");
		while( proc.runOnce() ){
			for( dm::scada::size_t task=1;task<tm.size();++task ){
				const CTaskInfo* ti = tm.info(task);
				if( ti==NULL ){
					log().error(STATICMODULE "can not find task %d info",task);
					continue;
				}

				const CTaskStatus* tt = tm.status(task);
				if( tt==NULL ){
					log().error(STATICMODULE "can not find task %d status",task);
					continue;
				}

				if( !tt->isRunning() && ti->isAutoStart() ){
					if( tt->nextRun!=CTaskStatus::NoTime && time(NULL)>=tt->nextRun ){
						log().info(STATICMODULE "time to start task %d",task);

						// 创建子进程，执行命令
						if( execTask(ti->cmd.c_str(),ti->args.c_str()) )
							log().info(STATICMODULE "start task %d success",task);
						else
							log().error(STATICMODULE "can not start task %d %s:%s",task,ti->cmd.c_str(),ti->args.c_str());
					}
				}
			}
			proc.delay(1);
		}

		log().debug(STATICMODULE "exit daemon dm_initd");
	}

	return 0;
}




